﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace DSServer.Communication
{
    class CommunicatorI : CommunicatorDisp_
    {
        //to be strict I should lock user for whole conversation, but I do it only for logging, I hope it's not a big deal.
        private readonly object accountLocker = new object();
        private readonly object roomLocker = new object();
        private readonly string accountDirectory = "CommunicationAccounts";
        private readonly string roomDirectory = "CommunicationRooms";

        private string accountPath(string filename)
        {
            return accountDirectory + "/" + filename;
        }

        private string roomPath(string filename)
        {
            return roomDirectory + "/" + filename;
        }


        public override void createAccount(string login, string password, Ice.Current current__)
        {
            lock (accountLocker)
            {
                if(File.Exists(accountPath(login)))
                    throw new LoginAlreadyUsedException();
                File.WriteAllText(accountPath(login), password);
            }
        }

        public override void destroyAccount(string login, string password, Ice.Current current__)
        {
            lock (accountLocker)
            {
                if(!File.Exists(accountPath(login)))
                    throw new InvalidLoginOrPasswordException();
                if (File.ReadAllText(accountPath(login)) != password)
                    throw new InvalidLoginOrPasswordException();
                File.Delete(login);
            }
        }

        public override void createRoom(string name, Ice.Current current__)
        {
            lock (roomLocker)
            {
                if(File.Exists(roomPath(name)))
                    throw new RoomAlreadyExistsException();
                File.WriteAllText(roomPath(name),"");
            }
        }

        public override void destroyRoom(string name, Ice.Current current__)
        {
            lock (roomLocker)
            {
                if (!File.Exists(roomPath(name)))
                    throw new RoomNotExistsException();
                try
                {
                    File.Delete(roomPath(name));
                }
                catch (UnauthorizedAccessException e)
                {
                }
            }
        }


    }
}
